package jnpf.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.common.enums.dify.DifyAITypeEnum;
import jnpf.exception.DataException;
import jnpf.model.objRelation.ModelListResp;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.know.api.*;
import jnpf.permission.entity.UserEntity;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.agent.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.*;
import jnpf.annotation.JnpfField;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.exception.WorkFlowException;
import org.springframework.web.multipart.MultipartFile;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.File;
import jnpf.onlinedev.model.ExcelImFieldModel;
import jnpf.onlinedev.model.OnlineImport.ImportDataModel;
import jnpf.onlinedev.model.OnlineImport.ImportFormCheckUniqueModel;
import jnpf.onlinedev.model.OnlineImport.ExcelImportModel;
import jnpf.onlinedev.model.OnlineImport.VisualImportModel;
import cn.xuyanwu.spring.file.storage.FileInfo;
import lombok.Cleanup;
import jnpf.model.visualJson.config.HeaderModel;
import jnpf.base.model.ColumnDataModel;
import jnpf.base.util.VisualUtils;
import org.springframework.transaction.annotation.Transactional;

import static jnpf.common.enums.dify.DifyAITypeEnum.getCodeByType;

/**
 * agent
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-05-25
 */
@Slf4j
@RestController
@Tag(name = "agent" , description = "example")
@RequestMapping("/api/example/Agent")
public class AgentController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AgentService agentService;



    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DifyKnowService difyKnowService;

    @Autowired
    private Environment environment;

    /**
    * 列表
    *
    * @param agentPagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody AgentPagination agentPagination)throws IOException{
        List<AgentEntity> list= agentService.getList(agentPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (AgentEntity entity : list) {
        Map<String, Object> agentMap=JsonUtil.entityToMap(entity);
        agentMap.put("id", agentMap.get("id"));
        //副表数据
        //子表数据
            realList.add(agentMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, AgentConstant.getFormData(), AgentConstant.getColumnData(), agentPagination.getModuleId(),false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(agentPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }
    /**
    * 创建
    *
    * @param agentForm
    * @return
    */
    @PostMapping("/save")
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid AgentForm agentForm) {
//        String b = agentService.checkForm(agentForm,0);
//        if (StringUtil.isNotEmpty(b)){
//            return ActionResult.fail(b );
//        }

        try{
            AgentEntity agentEntity = agentService.saveOrUpdate(agentForm, null, true);

            String mold = agentForm.getMold().toString();
            if(mold.equals("1")){
                String name = agentForm.getName();
                String assistantdes = agentForm.getAssistantdes();
                //知识库，逗号分隔
                String know = agentForm.getKnow();
                //系统提示此
                String syswords = agentForm.getSyswords();
                //知识库名称
                String modelName = agentForm.getModel().toString();

                AssistantConfig assistantConfig=loadDefaultAssistantConfig();
                assistantConfig.setName(name);
                assistantConfig.setDescription(assistantdes);
                assistantConfig.setLlm_id(modelName);

                PromptConfig promptConfig=new PromptConfig();
                promptConfig.setSystem(syswords);

                assistantConfig.setPrompt_config(promptConfig);

                if(StrUtil.isNotEmpty(know)){
                    if(know.contains(",")){
                        String[] split = know.split(",");
                        assistantConfig.setKb_ids(split);
                    }else{
                        assistantConfig.setKb_ids(new String[]{know});
                    }
                    Parameter parameter=new Parameter();
                    parameter.setOptional(true);
                    promptConfig.setParameters(new Parameter[]{parameter});
                }


                RagFlowApiResult<AssistantConfigResp> assistantConfigRagFlowApiResult = difyKnowService.saveAssistant(assistantConfig);

                if(assistantConfigRagFlowApiResult.getCode()!=0){
                    String msg=assistantConfigRagFlowApiResult.getMessage();
                    return ActionResult.fail("新增助手失败:"+msg);
                }else{
                    AssistantConfigResp data = assistantConfigRagFlowApiResult.getData();
                    agentEntity.setAiid(data.getId());
                    agentService.updateById(agentEntity);
                }
            }
        }catch(Exception e){
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }
    /**
    * 导出Excel
    *
    * @return
    */
    @Operation(summary = "导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody AgentPagination agentPagination) throws IOException {
        if (StringUtil.isEmpty(agentPagination.getSelectKey())){
            return ActionResult.fail("请选择导出字段");
        }
        List<AgentEntity> list= agentService.getList(agentPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (AgentEntity entity : list) {
        Map<String, Object> agentMap=JsonUtil.entityToMap(entity);
        agentMap.put("id", agentMap.get("id"));
        //副表数据
        //子表数据
            realList.add(agentMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, AgentConstant.getFormData(), AgentConstant.getColumnData(), agentPagination.getModuleId(),false);
        String[]keys=!StringUtil.isEmpty(agentPagination.getSelectKey())?agentPagination.getSelectKey():new String[0];
        UserInfo userInfo=userProvider.get();
            DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),realList,keys,userInfo);
        return ActionResult.success(vo);
    }

    /**
    * 导出表格方法
    */
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo){
        DownloadVO vo=DownloadVO.builder().build();
        List<ExcelExportEntity> entitys=new ArrayList<>();
        if(keys.length>0){
            for(String key:keys){
                switch(key){
                    case "name" :
                    entitys.add(new ExcelExportEntity("助理名称" ,"name"));
                    break;
                    case "assistantdes" :
                    entitys.add(new ExcelExportEntity("助手描述" ,"assistantdes"));
                    break;
                    case "img" :
                    entitys.add(new ExcelExportEntity("助理头像" ,"img"));
                    break;
                    case "nullback" :
                    entitys.add(new ExcelExportEntity("空回复" ,"nullback"));
                    break;
                    case "mold" :
                    entitys.add(new ExcelExportEntity("类型" ,"mold"));
                    break;
                    case "quotation" :
                    entitys.add(new ExcelExportEntity("引文" ,"quotation"));
                    break;
                    case "tospeech" :
                    entitys.add(new ExcelExportEntity("文本转语音" ,"tospeech"));
                    break;
                    case "wordanalysis" :
                    entitys.add(new ExcelExportEntity("关键字分析" ,"wordanalysis"));
                    break;
                    case "tak" :
                    entitys.add(new ExcelExportEntity("TavilyApikey" ,"tak"));
                    break;
                    case "know" :
                    entitys.add(new ExcelExportEntity("知识库" ,"know"));
                    break;
                    case "model" :
                    entitys.add(new ExcelExportEntity("模型" ,"model"));
                    break;
                    case "prologue" :
                    entitys.add(new ExcelExportEntity("开场白" ,"prologue"));
                    break;
                    case "syswords" :
                    entitys.add(new ExcelExportEntity("系统提示词" ,"syswords"));
                    break;
                    case "similaritythreshold" :
                    entitys.add(new ExcelExportEntity("相似度阙值" ,"similaritythreshold"));
                    break;
                    case "similarityweight" :
                    entitys.add(new ExcelExportEntity("相似度权重" ,"similarityweight"));
                    break;
                    case "topn" :
                    entitys.add(new ExcelExportEntity("TopN" ,"topn"));
                    break;
                    case "dialogueoptimization" :
                    entitys.add(new ExcelExportEntity("多轮对话优化" ,"dialogueoptimization"));
                    break;
                    case "knowledge" :
                    entitys.add(new ExcelExportEntity("使用知识图谱" ,"knowledge"));
                    break;
                    case "reasoning" :
                    entitys.add(new ExcelExportEntity("推理" ,"reasoning"));
                    break;
                    case "rerankmodel" :
                    entitys.add(new ExcelExportEntity("Rerank模型" ,"rerankmodel"));
                    break;
                    case "var" :
                    entitys.add(new ExcelExportEntity("变量" ,"var"));
                    break;
                    case "dof" :
                    entitys.add(new ExcelExportEntity("自由度" ,"dof"));
                    break;
                    case "temperature" :
                    entitys.add(new ExcelExportEntity("温度" ,"temperature"));
                    break;
                    case "topp" :
                    entitys.add(new ExcelExportEntity("TopP" ,"topp"));
                    break;
                    case "therepenalties" :
                    entitys.add(new ExcelExportEntity("存在处罚" ,"therepenalties"));
                    break;
                    case "frequencypenalty" :
                    entitys.add(new ExcelExportEntity("频率处罚" ,"frequencypenalty"));
                    break;
                    case "agentid" :
                    entitys.add(new ExcelExportEntity("智能体id" ,"agentid"));
                    break;
                    case "createuserid" :
                    entitys.add(new ExcelExportEntity("创建人id" ,"createuserid"));
                    break;
                    case "createtime" :
                    entitys.add(new ExcelExportEntity("创建时间" ,"createtime"));
                    break;
                    default:
                    break;
                }
            }
        }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size()>0){
                if (list.size()==0){
                    list.add(new HashMap<>());
                }
                //去除空数据
                List<Map<String, Object>> dataList = new ArrayList<>();
                for (Map<String, Object> map : list) {
                    int i = 0;
                    for (String key : keys) {
                        //子表
                        if (key.toLowerCase().startsWith("tablefield")) {
                            String tableField = key.substring(0, key.indexOf("-" ));
                            String field = key.substring(key.indexOf("-" ) + 1);
                            Object o = map.get(tableField);
                            if (o != null) {
                                List<Map<String, Object>> childList = (List<Map<String, Object>>) o;
                                for (Map<String, Object> childMap : childList) {
                                    if (childMap.get(field) != null) {
                                        i++;
                                    }
                                }
                            }
                        } else {
                            Object o = map.get(key);
                            if (o != null) {
                                i++;
                            }
                        }
                    }
                    if (i > 0) {
                        dataList.add(map);
                    }
                }
                //复杂表头-表头和数据处理
                ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(AgentConstant.getColumnData(), ColumnDataModel.class);
                List<HeaderModel> complexHeaderList = columnDataModel.getComplexHeaderList();
                if (!Objects.equals(columnDataModel.getType(), 3) && !Objects.equals(columnDataModel.getType(), 5)) {
                    entitys = VisualUtils.complexHeaderHandel(entitys, complexHeaderList);
                    dataList =  VisualUtils.complexHeaderDataHandel(dataList, complexHeaderList);
                }

                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
            }
            String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
            String temporaryFilePath = configValueUtil.getTemporaryFilePath();
            FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
            vo.setName(fileInfo.getFilename());
            vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids) throws Exception {
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
        return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 编辑
    * @param id
    * @param agentForm
    * @return
    */
    @PutMapping("/update/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid AgentForm agentForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        agentForm.setId(id);
        if (!isImport) {
            String b =  agentService.checkForm(agentForm,1);
            if (StringUtil.isNotEmpty(b)){
                return ActionResult.fail(b );
            }
        }
        AgentEntity entity= agentService.getInfo(id);
        if(entity!=null){
            try{
                AgentEntity agentEntity = agentService.saveOrUpdate(agentForm, id, false);

                String mold = agentForm.getMold().toString();
                if(mold.equals("1")){
                    String name = agentForm.getName();
                    String assistantdes = agentForm.getAssistantdes();
                    //知识库，逗号分隔
                    String know = agentForm.getKnow();
                    //系统提示此
                    String syswords = agentForm.getSyswords();
                    //知识库名称
                    String modelName = agentForm.getModel().toString();

                    AssistantConfigReq assistantConfig=loadDefaultAssistantConfigReq();
                    assistantConfig.setDialog_id(entity.getAiid());
                    assistantConfig.setName(name);
                    assistantConfig.setDescription(assistantdes);
                    assistantConfig.setLlm_id(modelName);

                    PromptConfig promptConfig=new PromptConfig();
                    promptConfig.setSystem(syswords);

                    assistantConfig.setPrompt_config(promptConfig);

                    if(StrUtil.isNotEmpty(know)){
                        if(know.contains(",")){
                            String[] split = know.split(",");
                            assistantConfig.setKb_ids(split);
                        }else{
                            assistantConfig.setKb_ids(new String[]{know});
                        }
                        Parameter parameter=new Parameter();
                        parameter.setOptional(true);
                        promptConfig.setParameters(new Parameter[]{parameter});
                    }
                    RagFlowApiResult<AssistantConfigResp> assistantConfigRespRagFlowApiResult = difyKnowService.updateAssistant(assistantConfig);
                    if(assistantConfigRespRagFlowApiResult.getCode()!=0){
                        String msg=assistantConfigRespRagFlowApiResult.getMessage();
                        return ActionResult.fail("更新助手失败:"+msg);
                    }
                }
            }catch(Exception e){
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) throws Exception {
        AgentEntity entity= agentService.getInfo(id);
        if(entity!=null){
            if(entity.getMold().equals("1")){
                //rag助手删除
                RagFlowApiResult ragFlowApiResult = difyKnowService.deleteAssistant(entity);
                if(ragFlowApiResult.getCode()!=0){
                    String msg=ragFlowApiResult.getMessage();
                    return ActionResult.fail(msg);
                }
            }else{
                //Dify助手删除
                RagFlowApiResult ragFlowApiResult = difyKnowService.deleteAssistant(entity);
                if(ragFlowApiResult.getCode()!=0){
                    String msg=ragFlowApiResult.getMessage();
                    return ActionResult.fail(msg);
                }
            }
            agentService.delete(entity);
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        AgentEntity entity= agentService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> agentMap=JsonUtil.entityToMap(entity);
        agentMap.put("id", agentMap.get("id"));
        agentMap.put("mold",entity.getMold());

        //副表数据
        //子表数据
        agentMap = generaterSwapUtil.swapDataDetail(agentMap,AgentConstant.getFormData(),"695530720881309573",false);
        return ActionResult.success(agentMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        AgentEntity entity= agentService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> agentMap=JsonUtil.entityToMap(entity);
        agentMap.put("id", agentMap.get("id"));
        //副表数据
        //子表数据
        agentMap = generaterSwapUtil.swapDataForm(agentMap,AgentConstant.getFormData(),AgentConstant.TABLEFIELDKEY,AgentConstant.TABLERENAMES);
        return ActionResult.success(agentMap);
    }




    private AssistantConfigReq loadDefaultAssistantConfigReq() {
        AssistantConfigReq config = new AssistantConfigReq();

        // 基础配置
        config.setDialog_id(environment.getProperty("ragflow.assistant.dialog_id", ""));
        config.setName(environment.getProperty("ragflow.assistant.name", ""));
        config.setDescription(environment.getProperty("ragflow.assistant.description", ""));
        config.setIcon(environment.getProperty("ragflow.assistant.icon", ""));
        config.setLanguage(environment.getProperty("ragflow.assistant.language", "English"));
        config.setLlm_id(environment.getProperty("ragflow.assistant.llm_id", "moonshot-v1-8k@Moonshot"));
        config.setSimilarity_threshold(Double.parseDouble(environment.getProperty("ragflow.assistant.similarity_threshold", "0.2")));
        config.setVector_similarity_weight(Double.parseDouble(environment.getProperty("ragflow.assistant.vector_similarity_weight", "0.3")));
        config.setTop_n(Integer.parseInt(environment.getProperty("ragflow.assistant.top_n", "8")));
        config.setRerank_id(environment.getProperty("ragflow.assistant.rerank_id", "gte-rerank@Tongyi-Qianwen"));
        config.setTop_k(Integer.parseInt(environment.getProperty("ragflow.assistant.top_k", "1024")));

        // 提示配置
        PromptConfig promptConfig = new PromptConfig();
        promptConfig.setEmpty_response(environment.getProperty("ragflow.assistant.prompt_config.empty_response", "抱歉，没找到您与您匹配的知识内容！"));
        promptConfig.setPrologue(environment.getProperty("ragflow.assistant.prompt_config.prologue", "你好！ 我是你的助理，有什么可以帮到你的吗？"));
        promptConfig.setQuote(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.quote", "true")));
        promptConfig.setKeyword(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.keyword", "true")));
        promptConfig.setTts(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.tts", "false")));
        promptConfig.setSystem(environment.getProperty("ragflow.assistant.prompt_config.system", ""));
        promptConfig.setRefine_multiturn(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.refine_multiturn", "false")));
        promptConfig.setUse_kg(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.use_kg", "true")));
        promptConfig.setReasoning(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.reasoning", "false")));
        String[] crossLanguages = environment.getProperty("ragflow.assistant.prompt_config.cross_languages", String[].class, new String[]{"Chinese"});
        promptConfig.setCross_languages(crossLanguages);

        Parameter[] parameters = new Parameter[1];
        Parameter parameter = new Parameter();
        parameter.setKey(environment.getProperty("ragflow.assistant.prompt_config.parameters[0].key", "knowledge"));
        parameter.setOptional(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.parameters[0].optional", "false")));
        parameters[0] = parameter;
        promptConfig.setParameters(parameters);

        config.setPrompt_config(promptConfig);
        // 大语言模型设置
        LlmSetting llmSetting = new LlmSetting();
        llmSetting.setTemperature(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.temperature", "0.1")));
        llmSetting.setTop_p(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.top_p", "0.3")));
        llmSetting.setPresence_penalty(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.presence_penalty", "0.4")));
        llmSetting.setFrequency_penalty(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.frequency_penalty", "0.7")));
        config.setLlm_setting(llmSetting);

        return config;
    }
    private AssistantConfig loadDefaultAssistantConfig() {
        AssistantConfig config = new AssistantConfig();

        // 基础配置
        config.setName(environment.getProperty("ragflow.assistant.name", ""));
        config.setDescription(environment.getProperty("ragflow.assistant.description", ""));
        config.setIcon(environment.getProperty("ragflow.assistant.icon", ""));
        config.setLanguage(environment.getProperty("ragflow.assistant.language", "English"));
        config.setLlm_id(environment.getProperty("ragflow.assistant.llm_id", "moonshot-v1-8k@Moonshot"));
        config.setSimilarity_threshold(Double.parseDouble(environment.getProperty("ragflow.assistant.similarity_threshold", "0.2")));
        config.setVector_similarity_weight(Double.parseDouble(environment.getProperty("ragflow.assistant.vector_similarity_weight", "0.3")));
        config.setTop_n(Integer.parseInt(environment.getProperty("ragflow.assistant.top_n", "8")));
        config.setRerank_id(environment.getProperty("ragflow.assistant.rerank_id", "gte-rerank@Tongyi-Qianwen"));
        config.setTop_k(Integer.parseInt(environment.getProperty("ragflow.assistant.top_k", "1024")));

        // 提示配置
        PromptConfig promptConfig = new PromptConfig();
        promptConfig.setEmpty_response(environment.getProperty("ragflow.assistant.prompt_config.empty_response", "抱歉，没找到您与您匹配的知识内容！"));
        promptConfig.setPrologue(environment.getProperty("ragflow.assistant.prompt_config.prologue", "你好！ 我是你的助理，有什么可以帮到你的吗？"));
        promptConfig.setQuote(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.quote", "true")));
        promptConfig.setKeyword(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.keyword", "true")));
        promptConfig.setTts(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.tts", "false")));
        promptConfig.setSystem(environment.getProperty("ragflow.assistant.prompt_config.system", ""));
        promptConfig.setRefine_multiturn(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.refine_multiturn", "false")));
        promptConfig.setUse_kg(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.use_kg", "true")));
        promptConfig.setReasoning(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.reasoning", "false")));
        String[] crossLanguages = environment.getProperty("ragflow.assistant.prompt_config.cross_languages", String[].class, new String[]{"Chinese"});
        promptConfig.setCross_languages(crossLanguages);

        Parameter[] parameters = new Parameter[1];
        Parameter parameter = new Parameter();
        parameter.setKey(environment.getProperty("ragflow.assistant.prompt_config.parameters[0].key", "knowledge"));
        parameter.setOptional(Boolean.parseBoolean(environment.getProperty("ragflow.assistant.prompt_config.parameters[0].optional", "false")));
        parameters[0] = parameter;
        promptConfig.setParameters(parameters);

        config.setPrompt_config(promptConfig);
        // 大语言模型设置
        LlmSetting llmSetting = new LlmSetting();
        llmSetting.setTemperature(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.temperature", "0.1")));
        llmSetting.setTop_p(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.top_p", "0.3")));
        llmSetting.setPresence_penalty(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.presence_penalty", "0.4")));
        llmSetting.setFrequency_penalty(Double.parseDouble(environment.getProperty("ragflow.assistant.llm_setting.frequency_penalty", "0.7")));
        config.setLlm_setting(llmSetting);

        return config;
    }

}
